<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"               
               @on-load="onLoad">
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   v-if="permission.dict_field_add"
                   @click.stop="openAutoGetFieldDialog">批量新增
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.dict_field_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuForm">
        <i class="el-icon-time history-icon"
           @click.stop="getHistoryRecord"></i>
      </template>
      <template slot="menuRight">
        <el-button type="default"  title="下载" @click.stop="exportExcel" icon="el-icon-download" circle size="small"></el-button>
      </template>
    </avue-crud>
    <!-- 
      批量添加数据对话框
     -->
    <el-dialog  title="变量标准化" 
      width='90%' 
      top="6vh"
      :close-on-click-modal='false' 
      :visible.sync="autoGetFieldDialog"
      destroy-on-close='true'
      center
      >
      <el-row>
        <el-col :span="4">
          <el-input
            type="textarea"
            :autosize="{ minRows: 20, maxRows: 20}"
            placeholder="可直接从excel粘贴中文变量"
            v-model="importDataArea"
            @change='handleImport'
            >
          </el-input>
        </el-col>
        <el-col :span="1">
        </el-col>
        <el-col :span="19">
          <el-table
            :data="autoFieldData"
            height="430"
            border
            v-loading="tabLoading"
            :row-class-name="tableRowClassName"
            style="width: 100%"
            >
            <el-table-column
              fixed
              prop="oldColumnComment"
              label="原名字"
              width="150">
            </el-table-column>
            <el-table-column
              prop="columnComment"
              label="标准化名字"
              width="150">
            </el-table-column>
            <el-table-column
              prop="columnName"
              label="标准化变量"
              width="200">
            </el-table-column>
            <el-table-column
              prop="dataTypeFmt"
              label="数据类型"
              width="120">
            </el-table-column>
             <el-table-column
              prop="likeColumnComment"
              label="相似变量"
              width="200">
            </el-table-column>
            <el-table-column
              prop="columnFullName"
              label="全名"
              width="200">
            </el-table-column>
            <el-table-column
              fixed="right"
              label="状态操作"
              width="120">
              <template slot-scope="scope">
                <el-button v-if="scope.row.foundFlag == 'root' || scope.row.foundFlag == 'find'"  @click="openAddToFieldDialog(scope.row)" type="text" size="small">添加到变量库</el-button>
                <el-tag  v-if="scope.row.foundFlag == 'field'"  >已在变量库</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'lostRoot'"  type="warning">缺失词根</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'lostAttrRoot'"  type="danger">缺失定语&词根</el-tag>
                <el-tag  v-if="scope.row.foundFlag == 'lostAttr'" type="success">缺失定语</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleImport($event)" data-clipboard-target="#pathText">开始标准化</el-button>
        <el-button size="small" @click="autoGetFieldDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      添加变量对话框
     -->
    <el-dialog :title="applyTitle" 
      width='40%' 
      top="6vh"
      :show-close='false'
      :close-on-click-modal='false' 
      :visible.sync="applyFieldDialog">
      <avue-form ref="applyRef" v-model="applyForm" :option="applyOption" @reset-change="emptytChange"  @submit='submitAddToField' >
        <template slot-scope="scope" slot="menuForm">
          <!-- <el-button type="primary"
                   size="small"
                   icon="el-icon-check"
                   v-if="permission.dict_field_delete"
                   @click="submitAddToField">确 定
          </el-button>  -->
           <el-button type="default"
                   size="small"
                   icon="el-icon-close"
                   v-if="permission.dict_field_delete"
                   @click="cancelApplyDialog">取 消
          </el-button> 
        </template>
      </avue-form>
    </el-dialog>

    <!-- 历史记录 -->
    <updateHistory ref="historyRecord"></updateHistory>
  </basic-container>
</template>

<script>
import {exportSysToolDictFieldExcel,autoGetSysToolDictFieldList,saveOrUpdateSysToolDictField,saveOrUpdateSysToolDictFieldList,saveSysToolDictField,saveSysToolDictFieldList,deleteSysToolDictField,querySysToolDictField,querySysToolDictFieldListPage,updateSysToolDictField,deleteSysToolDictFieldList} from '@/api/tool/sysToolDictFieldApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import updateHistory from '../../components/history/update-history'
export default {
  components: {
    updateHistory
  },
  data() {
    return {
      //修改历史对话框控制
      historyDialog: false,
      
      autoFieldData:[],
      tabLoading: false,
      importDataArea: 'ID\n租户ID',
      autoGetFieldDialog: false,
      applyFieldDialog: false,
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 120,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '字段名',
            prop: 'columnName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: true,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '字段说明',
            prop: 'columnComment', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入字段',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '数据类型',
            prop: 'dataType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请选择类型',
              trigger: 'blur'
            }],
            dicData:[{
              label:'varchar',
              value: 'varchar'
            },{
              label:'int',
              value: 'int'
            },{
              label:'char',
              value: 'char'
            },{
              label:'decimal',
              value: 'decimal'
            },{
              label:'datetime',
              value: 'datetime'
            },{
              label:'bigint',
              value: 'bigint'
            },{
              label:'text',
              value: 'text'
            }]
          },
          {
            label: '字段长度',
            prop: 'length', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入长度',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '小数点长度',
            prop: 'decimalLength', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '字段全名',
            prop: 'columnFullName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '申请系统',
            prop: 'applySystem', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '申请应用',
            prop: 'applyApp', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '申请人',
            prop: 'applyUserName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 0,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
        ]
      },
      data: [],

      // 申请信息对话框
      lastApplyForm:{},
      currFieldRow: {},
      applyTitle: '',
      applyForm:{},
      applyOption:{
        size:this.sizeValue,
        submitBtn: true,
        emptyBtn:false,
        printBtn:false,
        column: [{
          label: '申请系统',
          prop: 'applySystem',
          type: 'select',
          span: 24,
          rules: [{
            required: true,
            message: '请选择系统',
            trigger: 'blur'
          }],
          value: 'X光机',
          dicData:[
            {
              label:'X光机',
              value:'X光机'
            },
            {
              label:'核心系统',
              value:'核心系统'
            }
          ] 
        },
        {
          label: '申请应用',
          prop: 'applyApp',
          type: 'select',
          span: 24,
          rules: [{
            required: true,
            message: '请选择应用',
            trigger: 'blur'
          }],
          value: '公共平台',
          dicData:[
            {
              label:'公共平台',
              value:'公共平台'
            },
            {
              label:'宙斯',
              value:'宙斯'
            },
            {
              label:'雅典娜',
              value:'雅典娜'
            }
          ] 
        },
        {
          label: '申请人',
          prop: 'applyUserName',
          type: 'select',
          span: 24,
          rules: [{
            required: true,
            message: '请选择申请人',
            trigger: 'blur'
          }],
          value: '李秋宏',
          dicData:[
            {
              label:'李秋宏',
              value:'liqh'
            },
            {
              label:'李四',
              value:'LS'
            }
          ] 
        }
        ]
      },
      
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['permission','userInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.dict_field_add, false),
        viewBtn: this.vaildData(this.permission.dict_field_view, false),
        delBtn: this.vaildData(this.permission.dict_field_delete, false),
        editBtn: this.vaildData(this.permission.dict_field_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysToolDictFieldListPage(this.commonData).then(res => {
        
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysToolDictField(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysToolDictField(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysToolDictField(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }); 
    },
    /**
     * 批量新增记录
     */
    openAutoGetFieldDialog(){
      this.autoGetFieldDialog = true;
    },
    /**
     * 标准化数据
     */
    handleImport() {
      this.tabLoading=true;
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        var indx = 0;
        lineList.forEach((element,index) => {
          if(element != null && element.trim() != ''){
            var fieldList = {
              comment:element,
            }
            dataList[indx] = fieldList
            indx++;
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        autoGetSysToolDictFieldList(this.commonData).then(res => {
          this.tabLoading=false;
          this.autoFieldData = res.data.body.listBody;
        }, error => {
          //this.$console.log(error);
          this.tabLoading=false;
        });      
        //this.$console.log('lineList=',dataList)
      }
      else{
        this.tabLoading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据为空或不正确!'
        });
      }
    },
    /**
     *从标准化新增变量
     */
    openAddToFieldDialog(row){
      this.applyTitle = '确定将变量「'+row.columnComment+'」添加到变量库？';
      this.applyFieldDialog = true;
      this.currFieldRow = row; 
    },
    cancelApplyDialog(){
      this.applyFieldDialog = false;
    },
    submitAddToField(form,done) {
      //this.$console.log(this.currFieldRow);
      var fieldRow = {
        columnName: this.currFieldRow.columnName,
        columnComment: this.currFieldRow.columnComment,
        dataType: this.currFieldRow.dataType,
        length: this.currFieldRow.length,
        decimalLength: this.currFieldRow.decimalLength,
        columnFullName: this.currFieldRow.columnFullName,
        applySystem: this.applyForm.applySystem,
        applyApp: this.applyForm.applyApp,
        applyUserName:this.applyForm.applyUserName
      }
      this.reqParams.singleBody = fieldRow;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysToolDictField(this.commonData).then(() => {
        done()
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        this.applyFieldDialog = false;
        //更新表格状态 利用浅拷贝原理
        this.currFieldRow.foundFlag = 'field';
        // this.autoFieldData.forEach((element,index) => {
        //   if(element.columnComment.trim() == this.currFieldRow.columnComment.trim()){
        //     element.foundFlag = 'field';
        //   }
        // });
      }, error => {
        //this.$console.log(error);
        done()
        this.applyFieldDialog = false;
      });         
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysToolDictFieldList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        querySysToolDictField(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportSysToolDictFieldExcel(this.commonData);
    },
    tableRowClassName({row, rowIndex}) {
      if (row.foundFlag === 'field') {
        return 'in-field-row';
      } else if (row.foundFlag === 'root') {
        return 'in-root-row';
      }
      else {
        return '';
      } 
    },
    // 修改历史
    openHistoryDialog(){
      //this.$console.log('修改历史....');
      this.historyDialog = true;
    },
    //历史记录方法
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id, 'SysToolDictFieldEntity');
      })
    },
  },
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'sysToolDictFieldColumn'});
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'sysToolDictFieldColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'sysToolDictFieldColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
  .el-table .in-field-row {
    background:lightgreen !important;
  }

  .el-table .in-root-row {
    background:powderblue !important;
  }
  .history-icon{
    font-size: 30px;
    right: 40px;
    color: rgb(3, 167, 253);
    display: inline-block;
    position: absolute;
  }
</style>
